/**
 * @description 后端入口文件
 */
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const path = require('path')
const { StockService } = require('./services/stockService')
const { PredictionService } = require('./services/predictionService')
const cors = require('koa2-cors')
const dotenv = require('dotenv')

// 根据环境加载配置
const envPath = process.env.NODE_ENV === 'production' 
  ? path.resolve(__dirname, '../.env.production')
  : path.resolve(__dirname, '../.env')

dotenv.config({ path: envPath })

const app = new Koa()
const router = new Router()

// 生产环境下的安全配置
if (process.env.NODE_ENV === 'production') {
  app.use(async (ctx, next) => {
    ctx.set('X-Content-Type-Options', 'nosniff')
    ctx.set('X-Frame-Options', 'DENY')
    ctx.set('X-XSS-Protection', '1; mode=block')
    await next()
  })
}

app.use(cors())
app.use(bodyParser())

// API路由
router.get('/api/stocks', async (ctx) => {
  try {
    const stockService = new StockService()
    const predictionService = new PredictionService()
    
    const stocks = await stockService.getStockList()
    const predictions = await predictionService.generatePredictions(stocks)
    
    // 按涨跌幅排序
    const sortedStocks = [...predictions].sort((a, b) => Math.abs(b.changePercent) - Math.abs(a.changePercent))
    
    // 分别获取涨跌幅榜
    const gainers = sortedStocks.filter(s => s.changePercent > 0)
    const losers = sortedStocks.filter(s => s.changePercent < 0)
    ctx.body = {
      topGainers: gainers.slice(0, 1000),
      topLosers: losers.slice(0, 200),
      recommendations: predictions
        .filter(p => ['强烈推荐', '建议买入', '可以关注'].includes(p.recommendation))
        .sort((a, b) => b.predictionScore - a.predictionScore)
        .slice(0, 20)
    }
  } catch (error) {
    ctx.status = 500
    ctx.body = { error: error.message }
  }
})

app.use(router.routes())
app.use(router.allowedMethods())

const port = process.env.PORT || 3000
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`)
}) 